package model;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-19
 * Time：22:07
 */
public class EmployeeDao {
    public List<Employee> selectAll() {
        List<Employee> employees = new ArrayList<>();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://127.0.0.1:3306/jsp_test?characterEncoding=utf8&useSSL=false";
            connection = DriverManager.getConnection(url,"root","sj135433");
            statement = connection.createStatement();
            String sql = "select * from employee";
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                Employee employee =  new Employee();
                employee.setId(resultSet.getInt("id"));
                employee.setName(resultSet.getString("name"));
                employee.setHireDate(resultSet.getDate("hire_date"));
                employee.setSalary(resultSet.getInt("salary"));
                System.out.println(employee);
                employees.add(employee);
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return employees;
    }
}
